package com.ywc.tool;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;

public class PermissionUtil {
    //判断权限是否打开
    public static boolean isOpen(Activity context, int code, String ...permissions)
    {
        List<String> permissionsList = new ArrayList<>();
        for (String key : permissions) {
            //权限未打开的
            if (ContextCompat.checkSelfPermission(context, key) != PackageManager.PERMISSION_GRANTED) {
                //未打开的权限
                permissionsList.add(key);
            }
        }
        if (permissionsList.size() > 0)
        {
            ActivityCompat.requestPermissions(context, permissionsList.toArray(new String[permissionsList.size()]), code);
            return false;
        }
        return true;
    }

    //最后查看权限是否全部打开
    public static List<String> processing(@NonNull String[] permissions, @NonNull int[] grantResults)
    {
        List<String> failurePermissions = new ArrayList<>();
        for (int i = 0; i < grantResults.length; i++)
        {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED)
            {
                failurePermissions.add(permissions[i]);
            }
        }
        //权限全部打开了
        if (failurePermissions.size() == 0)
        {
            return null;
        }
        else
        {
            return failurePermissions;
        }
    }

}
